<!--
@description    表格展示
@author         秦俊强
@email          458112865@qq.com
@create         2021-06-07
-->

<template>
  <div class="content">
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="600"
      row-key="id"
      border
      stripe
      highlight-current-row
      id="rebateSetTable"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        v-for="(item, index) in tableHead"
        :key="index"
        :label="item.label"
        :property="item.prop"
        :align="index > 1 ? 'right' : ''"
        :width="index === 0 ? '45px' : ''"
      >
        <template slot-scope="scope">
          <div v-if="isArray(scope.row[scope.column.property])">
            <div
              v-for="(item, ind) in scope.row[scope.column.property]"
              :key="ind"
              :style="{ color: ind === 1 ? '#0AA372' : '' }"
            >
              {{ item }}
            </div>
          </div>

          <div v-else>{{ scope.row[scope.column.property] }}</div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "table-funnel",

  props: {
    //通过什么查看
    byXXXReadValues: {
      type: Object,
      default: "",
    },
    ltvReportResData: {
      type: Object,
      default: null,
    },
    ltvReportByValues: {
      type: Array,
      default: null,
    },
    /* 视图类型 */
    state: {
      type: String,
      default: null,
    }, // trends 趋势 | contrast 对比
    currentContrastStep: {
      type: Number,
      default: 0,
    },
  },

  data() {
    return {
      tableHead: [],
      tableData: [],
    };
  },

  created() {
    let t = this;
    t.tableHead = [];
    t.tableData = [];

    t.$watch("ltvReportResData", () => {
      // console.log('funnelReportResData = ', t.funnelReportResData);
      // console.log('funnelDetail = ', t.funnelReportResData.funnelDetail);

      t.tableHead = [];
      t.tableData = [];
      if (this.state === "trends") {
        t.initTabHeadTrends();
      } else {
        t.initTabHeadContrast();
      }
    });
  },

  methods: {
    exportExcel() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(
        document.querySelector("#rebateSetTable")
      );
      /* get binary string as output */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "计算结果.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    /* 判断是否是数组 */
    isArray: (a) => {
      return Object.prototype.toString.call(a) === "[object Array]";
    },

    /* 初始化表头 趋势*/
    initTabHeadTrends() {
      let t = this;
      if (
        t.ltvReportResData.rows !== undefined &&
        t.ltvReportResData.rows.length > 0
      ) {
        let dates = t.ltvReportResData.rows[0].cells;
        for (let i = 0; i < dates.length; i++) {
          if (i === 0) {
            t.tableHead.push({ prop: "", label: "" }); // 折叠展开箭头
            if (
              this.byXXXReadValues.cname !== undefined &&
              this.byXXXReadValues.cname !== "" &&
              this.byXXXReadValues.cname !== "总体"
            ) {
              t.tableHead.push({
                prop: "byValue",
                label: this.byXXXReadValues.cname,
              });
            }
            t.tableHead.push({ prop: "title", label: "指标" });
            t.tableHead.push({ prop: "totalPeople", label: "初始人数" });
            t.tableHead.push({ prop: i + "", label: "LTV 当天" });
          } else if (i < 8) {
            t.tableHead.push({ prop: i + "", label: "LTV " + i });
          } else if (i === 8) {
            t.tableHead.push({ prop: i + "", label: "LTV 15" });
          } else if (i === 9) {
            t.tableHead.push({ prop: i + "", label: "LTV 30" });
          } else if (i === 10) {
            t.tableHead.push({ prop: i + "", label: "LTV 60" });
          } else if (i === 11) {
            t.tableHead.push({ prop: i + "", label: "LTV 90" });
          }
        }
        t.initTabDataTrends();
      }
    },

    /* 初始化表身数据 趋势*/
    initTabDataTrends() {
      let t = this;

      let byValues = t.ltvReportByValues;
      // let byValues = t.ltvReportResData.rows;

      // 表身数据 byValues 的 length 表示一共有多少主行数
      if (byValues.length > 1) {
        byValues.unshift("总营收");
      }
      if (this.byXXXReadValues.cname === "总体") {
        for (let i = 0; i < byValues.length; i++) {
          let tabTem = t.getTabTem(true);

          tabTem.title = byValues[i];
          //主行数
          let itemEvent = t.ltvReportResData.rows[i];
          if (i === 0) {
            t.getRowDataAllDayEventTrends(tabTem, itemEvent.cells, false);
          } else {
            t.getRowDataAllDayEventTrends(tabTem, itemEvent.cells, true);
          }

          for (let j = 0; j < itemEvent.subRows.length; j++) {
            let cTabTem = t.getTabTem();
            cTabTem.title = itemEvent.subRows[j].byValue;
            cTabTem["totalPeople"] = itemEvent.subRows[j].totalPeople;
            if (i === 0) {
              tabTem.children.push(
                t.getRowDataAllDayEventTrends(
                  cTabTem,
                  itemEvent.subRows[j].cells,
                  false
                )
              );
            } else {
              tabTem.children.push(
                t.getRowDataAllDayEventTrends(
                  cTabTem,
                  itemEvent.subRows[j].cells,
                  true
                )
              );
            }
          }

          tabTem["totalPeople"] = t.ltvReportResData.rows[i].totalPeople;
          t.tableData.push(tabTem);
        }
      } else if (
        this.byXXXReadValues.cname !== undefined &&
        this.byXXXReadValues.cname !== ""
      ) {
        for (let i = 0; i < t.ltvReportResData.rows.length; i++) {
          for (let j = 0; j < byValues.length; j++) {
            let tabTem = t.getTabTem(true);
            if (
              t.ltvReportResData.rows[i].byValue === "" ||
              t.ltvReportResData.rows[i].byValue === undefined
            ) {
              tabTem.byValue = "未知";
            } else {
              tabTem.byValue = t.ltvReportResData.rows[i].byValue;
            }
            tabTem.title = byValues[j];

            //主行数
            let itemEvent = t.ltvReportResData.rows[i].subRows[j];
            if (j === 0) {
              t.getRowDataAllDayEventTrends(tabTem, itemEvent.cells, false);
            } else {
              t.getRowDataAllDayEventTrends(tabTem, itemEvent.cells, true);
            }

            for (let j = 0; j < itemEvent.subRows.length; j++) {
              let cTabTem = t.getTabTem();
              cTabTem.title = itemEvent.subRows[j].byValue;
              cTabTem["totalPeople"] = itemEvent.subRows[j].totalPeople;
              if (i === 0) {
                tabTem.children.push(
                  t.getRowDataAllDayEventTrends(
                    cTabTem,
                    itemEvent.subRows[j].cells,
                    false
                  )
                );
              } else {
                tabTem.children.push(
                  t.getRowDataAllDayEventTrends(
                    cTabTem,
                    itemEvent.subRows[j].cells,
                    true
                  )
                );
              }
            }

            tabTem["totalPeople"] =
              t.ltvReportResData.rows[i].subRows[j].totalPeople;
            t.tableData.push(tabTem);
          }
        }
      }
      this.$forceUpdate();

      // console.log('tableHead = ', t.tableHead);
      // console.log('tableData = ', t.tableData);
    },

    /* 初始化表头 对比*/
    initTabHeadContrast() {
      let t = this;
      if (t.ltvReportResData.rows.length <= 0) return;
      let dates = t.ltvReportResData.rows[0].subRows[0].subRows;
      if (this.byXXXReadValues.cname === "总体") {
        let dates = t.ltvReportResData.rows[0].subRows;
        for (let i = 0; i < dates.length; i++) {
          if (i === 0) {
            t.tableHead.push({ prop: "", label: "" }); // 折叠展开箭头
            t.tableHead.push({ prop: "title", label: "指标" });
            if (dates[i].cells.length > this.currentContrastStep) {
              t.tableHead.push({ prop: i + "", label: dates[i].byValue });
            }
          } else {
            if (dates[i].cells.length > this.currentContrastStep) {
              t.tableHead.push({ prop: i + "", label: dates[i].byValue });
            }
          }
        }
      } else {
        for (let i = 0; i < dates.length; i++) {
          if (i === 0) {
            t.tableHead.push({ prop: "", label: "" }); // 折叠展开箭头
            if (
              this.byXXXReadValues.cname !== undefined &&
              this.byXXXReadValues.cname !== "" &&
              this.byXXXReadValues.cname !== "总体"
            ) {
              t.tableHead.push({
                prop: "byValue",
                label: this.byXXXReadValues.cname,
              });
            }
            t.tableHead.push({ prop: "title", label: "指标" });
            if (dates[i].cells.length > this.currentContrastStep) {
              t.tableHead.push({ prop: i + "", label: dates[i].byValue });
            }
          } else {
            if (dates[i].cells.length > this.currentContrastStep) {
              t.tableHead.push({ prop: i + "", label: dates[i].byValue });
            }
          }
        }
      }
      this.initTabDataContrast();
    },

    /* 初始化表身 对比*/
    initTabDataContrast() {
      let t = this;
      let rows = t.ltvReportResData.rows;
      let byValues = t.ltvReportByValues;

      if (this.byXXXReadValues.cname === "总体") {
        if (t.ltvReportResData.rows.length > 1) {
          let dates = rows[0].subRows;
          // 表身数据 byValues 的 length 表示一共有多少主行数
          let tabTem = t.getTabTem(true);
          tabTem.title = "总营收";

          /* 总营收行*/
          for (let i = 0; i < dates.length; i++) {
            for (let j = 0; j < t.tableHead.length; j++) {
              if (dates[i].byValue === t.tableHead[j].label) {
                if (dates[i].cells.length <= this.currentContrastStep) {
                  tabTem[i] = "";
                } else {
                  tabTem[i] = dates[i].cells[this.currentContrastStep].amount;
                }
              }
            }
          }

          /* 其他行*/
          for (
            let otherLineIndex = 0;
            otherLineIndex < rows.length;
            otherLineIndex++
          ) {
            /* 除去总营收 其他类别*/
            if (otherLineIndex !== 0) {
              let cTabTem = t.getTabTem();
              cTabTem.title = byValues[otherLineIndex - 1];
              for (
                let otherLineIndexItem = 0;
                otherLineIndexItem < rows[otherLineIndex].subRows.length;
                otherLineIndexItem++
              ) {
                for (let k = 0; k < t.tableHead.length; k++) {
                  if (
                    rows[otherLineIndex].subRows[otherLineIndexItem].byValue ===
                    t.tableHead[k].label
                  ) {
                    if (
                      rows[otherLineIndex].subRows[otherLineIndexItem].cells
                        .length <= this.currentContrastStep
                    ) {
                      cTabTem[otherLineIndexItem] = "";
                    } else {
                      cTabTem[otherLineIndexItem] = [
                        rows[otherLineIndex].subRows[otherLineIndexItem].cells[
                          this.currentContrastStep
                        ].amount,
                        rows[otherLineIndex].subRows[otherLineIndexItem].cells[
                          this.currentContrastStep
                        ].percent,
                      ];
                    }
                  }
                }
              }
              tabTem.children.push(cTabTem);
            }
          }
          t.tableData.push(tabTem);
        } else {
          let tabTem = t.getTabTem(true);
          /* 其他行*/
          for (
            let otherLineIndex = 0;
            otherLineIndex < rows.length;
            otherLineIndex++
          ) {
            /* 除去总营收 其他类别*/
            tabTem.title = byValues[0];
            for (
              let otherLineIndexItem = 0;
              otherLineIndexItem < rows[otherLineIndex].subRows.length;
              otherLineIndexItem++
            ) {
              for (let k = 0; k < t.tableHead.length; k++) {
                if (
                  rows[otherLineIndex].subRows[otherLineIndexItem].byValue ===
                  t.tableHead[k].label
                ) {
                  if (
                    rows[otherLineIndex].subRows[otherLineIndexItem].cells
                      .length <= this.currentContrastStep
                  ) {
                    tabTem[otherLineIndexItem] = "";
                  } else {
                    tabTem[otherLineIndexItem] = [
                      rows[otherLineIndex].subRows[otherLineIndexItem].cells[
                        this.currentContrastStep
                      ].amount,
                    ];
                  }
                }
              }
            }
          }
          t.tableData.push(tabTem);
        }
      } else {
        for (let p = 0; p < rows.length; p++) {
          //如果营收事件只有一种则进入else处理
          if (rows[p].subRows.length > 1) {
            let dates = rows[p].subRows[0].subRows;
            // 表身数据 byValues 的 length 表示一共有多少主行数
            let tabTem = t.getTabTem(true);

            if (rows[p].byValue === undefined) {
              tabTem.byValue = "未知";
            } else {
              tabTem.byValue = rows[p].byValue;
            }
            tabTem.title = "总营收";

            /* 总营收行*/
            for (let i = 0; i < dates.length; i++) {
              for (let j = 0; j < t.tableHead.length; j++) {
                if (dates[i].byValue === t.tableHead[j].label) {
                  if (dates[i].cells.length <= this.currentContrastStep) {
                    tabTem[i] = "";
                  } else {
                    tabTem[i] = dates[i].cells[this.currentContrastStep].amount;
                  }
                }
              }
            }

            /* 其他行*/
            for (
              let otherLineIndex = 0;
              otherLineIndex < rows[p].subRows.length;
              otherLineIndex++
            ) {
              /* 除去总营收 其他类别*/
              if (otherLineIndex !== 0) {
                let cTabTem = t.getTabTem();
                cTabTem.title = byValues[otherLineIndex - 1];
                for (
                  let otherLineIndexItem = 0;
                  otherLineIndexItem <
                  rows[p].subRows[otherLineIndex].subRows.length;
                  otherLineIndexItem++
                ) {
                  for (let k = 0; k < t.tableHead.length; k++) {
                    if (
                      rows[p].subRows[otherLineIndex].subRows[
                        otherLineIndexItem
                      ].byValue === t.tableHead[k].label
                    ) {
                      if (
                        rows[p].subRows[otherLineIndex].subRows[
                          otherLineIndexItem
                        ].cells.length <= this.currentContrastStep
                      ) {
                        cTabTem[otherLineIndexItem] = "";
                      } else {
                        cTabTem[otherLineIndexItem] = [
                          rows[p].subRows[otherLineIndex].subRows[
                            otherLineIndexItem
                          ].cells[this.currentContrastStep].amount,
                          rows[p].subRows[otherLineIndex].subRows[
                            otherLineIndexItem
                          ].cells[this.currentContrastStep].percent,
                        ];
                      }
                    }
                  }
                }
                tabTem.children.push(cTabTem);
              }
            }
            t.tableData.push(tabTem);
          } else {
            let dates = rows[p].subRows[0].subRows;
            // 表身数据 byValues 的 length 表示一共有多少主行数
            let tabTem = t.getTabTem(true);

            if (rows[p].byValue === undefined) {
              tabTem.byValue = "未知";
            } else {
              tabTem.byValue = rows[p].byValue;
            }

            /* 其他行*/
            for (
              let otherLineIndex = 0;
              otherLineIndex < rows[p].subRows.length;
              otherLineIndex++
            ) {
              /* 除去总营收 其他类别*/
              tabTem.title = byValues[0];
              for (
                let otherLineIndexItem = 0;
                otherLineIndexItem <
                rows[p].subRows[otherLineIndex].subRows.length;
                otherLineIndexItem++
              ) {
                for (let k = 0; k < t.tableHead.length; k++) {
                  if (
                    rows[p].subRows[otherLineIndex].subRows[otherLineIndexItem]
                      .byValue === t.tableHead[k].label
                  ) {
                    if (
                      rows[p].subRows[otherLineIndex].subRows[
                        otherLineIndexItem
                      ].cells.length <= this.currentContrastStep
                    ) {
                      tabTem[otherLineIndexItem] = "";
                    } else {
                      tabTem[otherLineIndexItem] = [
                        rows[p].subRows[otherLineIndex].subRows[
                          otherLineIndexItem
                        ].cells[this.currentContrastStep].amount,
                      ];
                    }
                  }
                }
              }
            }
            t.tableData.push(tabTem);
          }
        }
      }
    },

    /* 返回数组字符串 例：['a', null] => 'a, null' */
    getByValuesListStr(arr) {
      let str = "";

      for (let i = 0; i < arr.length; i++) {
        let val = arr[i];
        str = str + val + (i === arr.length - 1 ? "" : ", ");
      }

      return str;
    },

    /* 返回表格行 */
    getRowDataAllDayEventTrends(resData, contrast, needPrice) {
      for (let i = 0; i < contrast.length; i++) {
        let item = contrast[i];
        if (i === 0 || needPrice === false) {
          resData[i] = item.amount;
        } else {
          resData[i] = [item.amount, item.percent + "%"];
        }
      }
      return resData;
    },
    getRowDataAllDayEventContrast(resData, contrast) {
      for (let i = 0; i < contrast.length; i++) {
        let item = contrast[i];
        resData[i] = [item.amount, item.percent + "%"];
      }
    },

    /* 返回表身数据模板 */
    getTabTem(b) {
      let tabTem = {};

      for (let i = 0; i < this.tableHead.length; i++) {
        let item = this.tableHead[i];

        // 标识唯一 id，方便折叠展开，和点击高亮行
        tabTem["id"] = Number(
          Math.random().toString().substr(3, 10) + Date.now()
        ).toString(36);

        if (item.prop) {
          tabTem[item.prop] = "";
        }

        if (b) {
          tabTem["children"] = [];
        }
      }

      return tabTem;
    },
  },
  watch: {
    state: function (val, oldval) {
      let t = this;
      t.tableHead = [];
      t.tableData = [];
      if (val === "trends") {
        this.initTabHeadTrends();
      } else if (val === "contrast") {
        this.initTabHeadContrast();
      }
    },
    currentContrastStep: function (val, oldval) {
      let t = this;
      t.tableHead = [];
      t.tableData = [];
      t.initTabHeadContrast();
    },
  },
};
</script>


<style scoped lang="scss">
::v-deep .el-table tbody td {
  padding: 5px 0;
}
</style>
